/**
 * Created by 01 on 2017/7/7.
 */
function OBJ_TO_PARAM(obj) {
  var rs = '';

  var arr = [];
  for (var k in obj) {
    if (obj.hasOwnProperty(k)) {
      arr.push(`${k}=${encodeURIComponent(obj[k])}`);
      // arr.push(`${k}=${obj[k]}`);
    }
    // rs += `${k}=${obj[k]}&`;
  }
  // 排序
  rs = arr.sort().join('&');
  // alert(rs);
  return rs;
}

function GET_XHR() {
  var xhr = '';
  if (window.XMLHttpRequest) {
    xhr = new XMLHttpRequest();
  } else {
    xhr = new ActiveXObject(' Microsoft . XMLHTTP')
  }
  return xhr;
}
/*
 * AJAX_POST
 * @param url
 * @param data {JSON}
 * @param cb
 * return (err,rs)
 * */
function AJAX_POST(url, data, cb, method) {
  var xhr = GET_XHR();
  var param = null;
  xhr.onreadystatechange = function () {
    if (xhr.readyState === 4 && cb) {
      if (xhr.status === 200)
        cb(null, xhr.responseText);
      else
        cb(new Error(xhr.status), xhr.responseText);
    }
  };

  // 异步 post,回调通知
  xhr.open('POST', url, 'true');
  if (data instanceof Object) param = OBJ_TO_PARAM(data); else param = data;
  xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  // xhr.setRequestHeader('Content-Type', 'text/plain; charset=utf-8');
  if (method) {
    xhr.setRequestHeader('X-AjaxPro-Method', method);
  }
  xhr.send(param);
}

/*
 * AJAX_GET
 * @param url
 * @param data {JSON}
 * @param cb
 * return (err,rs)
 * */
function AJAX_GET(url, data, cb, method) {
  var xhr = GET_XHR();
  var param = null;
  xhr.onreadystatechange = function () {
    if (xhr.readyState === 4 && cb) {
      if (xhr.status === 200)
        cb(null, xhr.responseText);
      else
        cb(new Error(xhr.status), xhr.responseText);
    }
  };

  if (data instanceof Object) param = OBJ_TO_PARAM(data); else param = data;

  // 异步 post,回调通知
  xhr.open('GET', url + '?' + param, 'true');
  xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  // xhr.setRequestHeader('Content-Type', 'text/plain; charset=utf-8');
  if (method) {
    xhr.setRequestHeader('X-AjaxPro-Method', method);
  }
  xhr.send(null);
}

// 异步post
function ASYNC_POST(url, data, cb, method) {
  try {
    if (CONFIG_URL) {
      AJAX_POST(CONFIG_URL.hcp + url, data, cb, method);
    } else
      AJAX_GET(HOST_URL + 'configUrl', '', function (err, rs) {
        // console.log('配置:', rs);
        if (rs) {
          var r = JSON.parse(rs);
          CONFIG_URL = r;
          AJAX_POST(r.hcp + url, data, cb, method);
        } else {
          console.log(new Error('您好！抱歉网络问题，请重试哦！'));
        }
      });
  } catch (e) {
    console.log(new Error('您好！抱歉网络问题，请重试哦！'));
  }
}